// 处理请求的封装
// let baseUrl="https://channingkiki.top/api"
import { baseUrl } from '@/config/index.js';
let isModalVisible = false; // 全局状态，标记当前是否有弹窗正在显示
const request = (config) => {
	// 处理 apiUrl
	config.url = baseUrl + config.url;
	if(!config.data) config.data = {};
	config.timeout = 300000;
    const token = uni.getStorageSync('token') || '';
    if (token) {
        if (!config.header) config.header = {};
        config.header['Authorization'] = `Bearer ${token}`;
    }
	
	let promise = new Promise(function(resolve, reject) {
		let noLoadingPaths = [];
		let shouldShowLoading = !noLoadingPaths.some(path => config.url.includes(path));

		if (shouldShowLoading) {
			
			uni.showLoading({
				title: '加载中',
				mask: true
			});
		}
		uni.request(config).then(responses => {
			uni.hideLoading();
			// 异常
			if (responses[0]) {
				reject({message : "网络超时"});
			} else {
				let response = responses.data; // 如果返回的结果是data.data的，嫌麻烦可以用这个，return res,这样只返回一个data'
				if(response.code == 401){
					uni.removeStorageSync('token');
					uni.removeStorageSync('userinfo');
					if (!isModalVisible) {
						isModalVisible = true; // 标记弹窗正在显示
						uni.showModal({
							title: "提示",
							// content: response.msg,
							content: '请先登录',
							showCancel: true,
							success: ({ confirm, cancel }) => {
							isModalVisible = false; // 弹窗关闭后重置状态
							if (confirm) {
								uni.reLaunch({
									url: "/pages/mine/login",
								});
							}
							if (cancel) {
								uni.navigateBack({
									delta: 1,
								});
							}
							},
							fail: () => {
							isModalVisible = false; // 弹窗关闭后重置状态
							},
						});
					}
				}else if(response.code == 500){
					uni.showToast({
						title: response.msg,
						icon: 'none',
					})
				}else{
					resolve(response);

				}
			}
		}).catch(error => {
			console.log(error);
			reject(error);
		})
	})
	return promise;
};

export default request;
